import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'
import UnoCSS from 'unocss/vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { defineConfig } from 'vite'
import compressionPlugin from 'vite-plugin-compression'
import vueDevTools from 'vite-plugin-vue-devtools'
import Layout from 'vite-plugin-vue-layouts'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
// eslint-disable-next-line no-undef
const pathResolve = (dir) => path.resolve(process.cwd(), dir)

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  return {
    base: './',
    plugins: [
      Layout({
        layoutsDirs: 'src/components/layouts',
        defaultLayout: 'default',
      }),
      vue(),
      UnoCSS({
        filePath: './uno.config.js',
      }),
      AutoImport({
        resolvers: [],
        imports: ['vue', 'vue-router'],
        vueTemplate: true,
        dts: 'src/auto-imports.d.ts',
        eslintrc: {
          enabled: true,
          filepath: './.eslintrc-auto-import.json',
          globalsPropValue: true,
        },
        dirs: ['src/components/common'],
      }),
      Components({
        extensions: ['vue'],
        resolvers: [],
      }),
      compressionPlugin({
        include: /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i,
        algorithm: 'gzip',
        filename: '[path][base].gz',
        threshold: 10240,
        level: mode === 'development' ? 1 : 9,
      }),
      vueDevTools(),
      createSvgIconsPlugin({
        iconDirs: [pathResolve('src/assets/icons')],
        symbolId: 'icon-[dir]-[name]',
        svgoOptions: {
          plugins: [
            {
              name: 'removeAttrs',
              params: { attrs: ['class', 'data-name', 'fill', 'stroke'] },
            },
          ],
        },
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    build: {
      minify: 'terser',
      reportCompressedSize: false, // 禁用压缩大小报告，加快构建
      cssCodeSplit: true, // CSS 代码分割
      sourcemap: mode === 'development', // 仅在开发环境生成 sourcemap
      assetsDir: 'assets', // 指定静态资源目录
      emptyOutDir: true, // 构建前清空目标目录
      terserOptions: {
        compress: {
          drop_console: true, // 移除 console
          drop_debugger: true, // 移除 debugger
          pure_funcs: ['console.log', 'console.info', 'console.warn', 'console.debug'], // 移除更多控制台函数
          dead_code: true, // 移除不可达代码
          loops: true, // 优化循环
          reduce_vars: true, // 优化变量
          pure_getters: true, // 优化 getter
          unused: true, // 删除未使用的变量和函数
          collapse_vars: true, // 内联可能的变量
          keep_fargs: false, // 删除未使用的函数参数
          passes: 2, // 压缩次数
          sequences: true, // 合并连续的简单语句
          conditionals: true, // 优化 if 语句和条件表达式
        },
        mangle: {
          toplevel: true, // 混淆顶级作用域中的变量名
          properties: false, // 是否混淆属性名
          safari10: true, // Safari 10 兼容性
          keep_classnames: false, // 不保留类名
          keep_fnames: false, // 不保留函数名
        },
        format: {
          comments: false, // 移除注释
          beautify: false, // 不美化输出
          indent_level: 0, // 压缩级别
          ascii_only: true, // 仅使用 ASCII 字符
        },
        toplevel: true, // 在顶级作用域中进行变量混淆
        nameCache: null, // 缓存混淆后的变量名
        ie8: false, // 不兼容 IE8
        safari10: true, // 兼容 Safari 10
        ecma: 2020, // 使用 ECMAScript 2020 规范
        keep_classnames: false, // 全局不保留类名
        keep_fnames: false, // 全局不保留函数名
      },
      rollupOptions: {
        chunkSizeWarningLimit: 1500,
        assetsInlineLimit: 8192, // 8 KB
        output: {
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
          manualChunks(id) {
            if (id.includes('node_modules')) {
              // 优化分包策略
              if (id.includes('vue') || id.includes('@vue')) {
                return 'vendor-vue'
              }
              if (id.includes('@vueuse') || id.includes('vue-use')) {
                return 'vendor-vueuse'
              }
              if (id.includes('lodash')) {
                return 'vendor-lodash'
              }
              if (id.includes('axios') || id.includes('http')) {
                return 'vendor-http'
              }
              if (id.includes('naive-ui')) {
                return 'vendor-ui'
              }
              return 'vendor'
            }
          },
        },
      },
    },
    server: {
      port: 9999,
    },
  }
})
